from django.shortcuts import render

# Create your views here.

# coding:utf-8
import tensorflow as tf
import numpy as np
import glob
import random
from PIL import Image
from skimage import io
import configparser
import os
import cv2
import numpy as np
import urllib
import base64

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

IMAGE_HEIGHT = 36
IMAGE_WIDTH = 120
MAX_CAPTCHA = 4
CHAR_SET_LEN = 63


def get_imgOld(image):
    GrayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    tmp = cv2.medianBlur(GrayImage, 1)

    ret, img = cv2.threshold(tmp, 170, 255, cv2.THRESH_BINARY_INV)

    kernel = np.ones((2, 2), np.uint8)

    img = cv2.dilate(img, kernel, iterations=1)

    img = cv2.erode(img, kernel, iterations=1)
    img = cv2.dilate(img, kernel, iterations=1)

    img = cv2.erode(img, kernel, iterations=1)
    img = cv2.medianBlur(img, 1)
    img = cv2.dilate(img, kernel, iterations=1)

    ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
    return img


def vec2text(vec):
    if not isinstance(vec, list):
        char_pos = vec.nonzero()[0]
    else:
        char_pos = vec
    text = []
    for i, c in enumerate(char_pos):
        char_idx = c % CHAR_SET_LEN
        if char_idx < 10:
            char_code = char_idx + ord('0')
        elif char_idx < 36:
            char_code = char_idx - 10 + ord('A')
        elif char_idx < 62:
            char_code = char_idx - 36 + ord('a')
        elif char_idx == 62:
            char_code = ord('_')
        text.append(chr(char_code))
    return "".join(text)


# 定义CNN
def crack_captcha_cnn(X, keep_prob, w_alpha=0.01, b_alpha=0.1):
    x = tf.reshape(X, shape=[-1, IMAGE_HEIGHT, IMAGE_WIDTH, 1])
    print(x.get_shape())

    # w_c1_alpha = np.sqrt(2.0/(IMAGE_HEIGHT*IMAGE_WIDTH)) #
    # w_c2_alpha = np.sqrt(2.0/(3*3*32))
    # w_c3_alpha = np.sqrt(2.0/(3*3*64))
    # w_d1_alpha = np.sqrt(2.0/(8*32*64))
    # out_alpha = np.sqrt(2.0/1024)

    # 3 conv layer
    w_c1 = tf.Variable(w_alpha * tf.random_normal([3, 3, 1, 32]))
    b_c1 = tf.Variable(b_alpha * tf.random_normal([32]))
    conv1 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(x, w_c1, strides=[1, 1, 1, 1], padding='SAME'), b_c1))
    conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
    conv1 = tf.nn.dropout(conv1, keep_prob)
    print(conv1.get_shape())

    w_c2 = tf.Variable(w_alpha * tf.random_normal([3, 3, 32, 64]))
    b_c2 = tf.Variable(b_alpha * tf.random_normal([64]))
    conv2 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv1, w_c2, strides=[1, 1, 1, 1], padding='SAME'), b_c2))
    conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
    conv2 = tf.nn.dropout(conv2, keep_prob)
    print(conv2.get_shape())

    w_c3 = tf.Variable(w_alpha * tf.random_normal([3, 3, 64, 64]))
    b_c3 = tf.Variable(b_alpha * tf.random_normal([64]))
    conv3 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv2, w_c3, strides=[1, 1, 1, 1], padding='SAME'), b_c3))
    conv3 = tf.nn.max_pool(conv3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
    conv3 = tf.nn.dropout(conv3, keep_prob)
    print(conv3.get_shape())

    # Fully connected layer
    w_d = tf.Variable(w_alpha * tf.random_normal([4800, 1024]))
    b_d = tf.Variable(b_alpha * tf.random_normal([1024]))
    dense = tf.reshape(conv3, [-1, w_d.get_shape().as_list()[0]])
    dense = tf.nn.relu(tf.add(tf.matmul(dense, w_d), b_d))
    dense = tf.nn.dropout(dense, keep_prob)

    w_out = tf.Variable(w_alpha * tf.random_normal([1024, MAX_CAPTCHA * CHAR_SET_LEN]))
    b_out = tf.Variable(b_alpha * tf.random_normal([MAX_CAPTCHA * CHAR_SET_LEN]))
    out = tf.add(tf.matmul(dense, w_out), b_out)
    # out = tf.nn.softmax(out)
    return out


tf.device('/cpu:0')
X = tf.placeholder(tf.float32, [None, IMAGE_HEIGHT * IMAGE_WIDTH])
keep_prob = tf.placeholder(tf.float32)
output = crack_captcha_cnn(X, keep_prob)
saver = tf.train.Saver()
sess = tf.Session()
saver.restore(sess, tf.train.latest_checkpoint('model/'))


def Index(request):

    fp = urllib.request.urlopen("http://www.ganji.com/common/checkcode.php?nocache=148793561879")
    data = fp.read()
    img64src = str(base64.b64encode(data).decode('utf8')).replace("'", "")
    img5 = np.asarray(bytearray(data), dtype="uint8")
    fp.close()
    # imgfrom=cv2.imdecode(img5, cv2.IMREAD_COLOR)
    imgfrom = cv2.imdecode(img5, 1)

    outimg = get_imgOld(imgfrom)
    captcha_image = outimg.flatten()
    predict = tf.argmax(tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)
    text_list = sess.run(predict, feed_dict={X: [captcha_image], keep_prob: 1})
    predict_text = text_list[0].tolist()
    predict_value = vec2text(predict_text)
    return HttpResponse(predict_value)


def SolveWithImageBase64(request, Base64String):
    data = base64.b64decode(Base64String.replace("-", "+").encode('utf8'))
    img5 = np.asarray(bytearray(data), dtype="uint8")
   # imgfrom=cv2.imdecode(img5, cv2.IMREAD_COLOR)
    imgfrom = cv2.imdecode(img5, 1)

    outimg = get_imgOld(imgfrom)
    captcha_image = outimg.flatten()
    predict = tf.argmax(tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)
    text_list = sess.run(predict, feed_dict={X: [captcha_image], keep_prob: 1})
    predict_text = text_list[0].tolist()
    predict_value = vec2text(predict_text)
    return HttpResponse( predict_value)

@csrf_exempt
def SolveWithImageBase64Post(request):
    Base64String= request.POST["Base64String"]
    data = base64.b64decode(Base64String.replace("-", "+").encode('utf8'))
    img5 = np.asarray(bytearray(data), dtype="uint8")
   # imgfrom=cv2.imdecode(img5, cv2.IMREAD_COLOR)
    imgfrom = cv2.imdecode(img5, 1)

    outimg = get_imgOld(imgfrom)
    captcha_image = outimg.flatten()
    predict = tf.argmax(tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)
    text_list = sess.run(predict, feed_dict={X: [captcha_image], keep_prob: 1})
    predict_text = text_list[0].tolist()
    predict_value = vec2text(predict_text)
    return HttpResponse( predict_value)



def SolveWithImageOrg(request):
    saver.restore(sess, tf.train.latest_checkpoint('model/'))
    fp = urllib.request.urlopen("http://www.ganji.com/common/checkcode.php?nocache=148793561879")
    data = fp.read()
    img64src = str(base64.b64encode(data).decode('utf8')).replace("'", "")
    img5 = np.asarray(bytearray(data), dtype="uint8")
    fp.close()
    # imgfrom=cv2.imdecode(img5, cv2.IMREAD_COLOR)
    imgfrom = cv2.imdecode(img5, 1)

    outimg = get_imgOld(imgfrom)
    captcha_image = outimg.flatten()
    predict = tf.argmax(tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)
    text_list = sess.run(predict, feed_dict={X: [captcha_image], keep_prob: 1})
    predict_text = text_list[0].tolist()
    predict_value = vec2text(predict_text)
    return HttpResponse("<img src='data:image/gif;base64,{}'> 识别结果:{}".format(img64src, predict_value))
